package controller

import (
	"fmt"
	"github.com/balance_foods/common"
	"github.com/balance_foods/global"
	"github.com/balance_foods/middleware"
	"github.com/balance_foods/model/basefile"
	"github.com/balance_foods/router"
	"github.com/balance_foods/utils"
	"github.com/gin-gonic/gin"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type FileApi struct {
}

func init() {

	fileApi := FileApi{}

	group := router.Router.Group("/file", middleware.Cors())

	{
		group.POST("/upload", fileApi.upload)

	}
}

func (FileApi) upload(ctx *gin.Context) {
	//获取普通文本
	// 获取文件(注意这个地方的file要和html模板中的name一致)
	file, err := ctx.FormFile("file")
	if err != nil {
		common.FailWithMessage("获取文件失败", ctx)
		return
	} else {
		//获取文件名称
		fmt.Println(file.Filename)
		//文件大小
		fmt.Println(file.Size)
		//获取文件的后缀名
		extstring := path.Ext(file.Filename)
		fmt.Println(extstring)
		//根据当前时间鹾生成一个新的文件名
		fileNameInt := time.Now().Unix()
		fileNameStr := strconv.FormatInt(fileNameInt, 10)
		//新的文件名
		fileName := fileNameStr + extstring
		//保存上传文件
		filePath := filepath.Join(utils.Mkdir("upload"), "/", fileName)
		err = ctx.SaveUploadedFile(file, filePath)
		if err != nil {
			common.FailWithErr(err, ctx)
			return
		}

		pathStr := strings.ReplaceAll(filePath, "upload", "")

		//pathStr = strings.ReplaceAll(pathStr, "/", "\\")

		baseFile := basefile.BaseFile{Name: fileName, Path: pathStr}

		global.Db.Save(&baseFile)

		common.SuccessWithData(baseFile, ctx)

		return

	}

}

func (FileApi) Static() {

}
